"nodejs";
console.log("233333333");
var http = require("http");
const os = require("os");
const Koa = require("koa");
const router = require("koa-router")();
var bodyParser = require("koa-bodyparser");
let handleMessage = require("./handleMessage.js");
let config = require("./config");
/* -------------------------------------------------------------------------- */
const port = config.port;
let engines = require("engines");
// 从参数中取出Rhino引擎的ID
const serverEngineId = engines.myEngine().execArgv.serverEngineId;
// 根据ID找出Rhino引擎
const serverEngine = engines.getRunningEngines().find((e) => e.id === serverEngineId);

/* -------------------------------------------------------------------------- */
var app = new Koa();
app.use(bodyParser());
/* -------------------------------------------------------------------------- */
router.get("/hello", async (ctx) => {
  console.log("hello");
  ctx.body = "router: hello world";
});
router.post("/group-msg", async (ctx) => {
  let postParam = ctx.request.body; //获取post提交的数据
  console.log("服务器收到的body");
  console.log(postParam);
  // 如果postParam没有三个字段: groupId, groupName, message, 那么就报错
  if (!postParam.groupId || !postParam.groupName || !postParam.message) {
    ctx.response.status = 400;
    ctx.body = "必须包含三个字段: groupId, groupName, message";
    return;
  }
  let data = await handleMessage(postParam);
  if (!data) {
    console.log("拒绝处理空消息");
    return false;
  }
  serverEngine.emit("reply", data);
  return (ctx.body = {
    code: 200,
    message: "成功",
    data: data,
  });
});

// 调用router.routes()来组装匹配好的路由，返回一个合并好的中间件
// 调用router.allowedMethods()获得一个中间件，当发送了不符合的请求时，会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
app.use(router.routes());
app.use(router.allowedMethods({}));
let localIp = getLocalIP();
app.listen(port, () => {
  console.log("koa is listening in " + localIp + ":" + port);
});

/**
 * 获取本机IP
 * @return {String} 返回本机IP
 */
function getLocalIP() {
  const ifaces = os.networkInterfaces();
  let localIp = "";
  for (let dev in ifaces) {
    for (let j = 0; j < ifaces[dev].length; j++) {
      if (ifaces[dev][j].family === "IPv4") {
        localIp = ifaces[dev][j].address;
        console.log("localIp: " + localIp);
        if (localIp === "127.0.0.1") {
          continue;
        } else {
          return localIp;
        }
      }
    }
  }
  if (!localIp) {
    throw new Error("无法获取本机IP");
  }
  return localIp;
}
